<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<meta name="generator" content="pdoc 0.9.1" />
<title>tronpytool.providers.http API documentation</title>
<meta name="description" content="tronpytool.providers.http
…" />
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/sanitize.min.css" integrity="sha256-PK9q560IAAa6WVRRh76LtCaI8pjTJ2z11v0miyNNjrs=" crossorigin>
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/typography.min.css" integrity="sha256-7l/o7C8jubJiy74VsKTidCy1yBkRtiUGbVkYBylBqUg=" crossorigin>
<link rel="stylesheet preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/styles/github.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/highlight.min.js" integrity="sha256-Uv3H6lx7dJmRfRvH8TH6kJD1TSK1aFcwgx+mdg3epi8=" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => hljs.initHighlighting())</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>tronpytool.providers.http</code></h1>
</header>
<section id="section-intro">
<h1 id="tronpytoolprovidershttp">tronpytool.providers.http</h1>
<p>Class for configuring http providers</p>
<p>:copyright: © 2018 by the iEXBase.
:license: MIT License</p>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">#!/usr/bin/env python
#
# --------------------------------------------------------------------
# Copyright (c) iEXBase. All rights reserved.
# Licensed under the MIT License.
# See License.txt in the project root for license information.
# --------------------------------------------------------------------


&#34;&#34;&#34;
    tronpytool.providers.http
    ======================

    Class for configuring http providers

    :copyright: © 2018 by the iEXBase.
    :license: MIT License
&#34;&#34;&#34;
import logging
from collections import namedtuple
from urllib.parse import urlparse

from eth_utils import to_dict
from requests import Session
from requests.exceptions import (
    ConnectionError as TrxConnectionError
)

from tronpytool.common.encoding import to_text
from tronpytool.exceptions import HTTP_EXCEPTIONS, TransportError
from tronpytool.providers.base import BaseProvider

HTTP_SCHEMES = {&#39;http&#39;, &#39;https&#39;}
HttpResponse = namedtuple(&#39;HttpResponse&#39;, (&#39;status_code&#39;, &#39;headers&#39;, &#39;data&#39;))

log = logging.getLogger(__name__)


def is_valid_provider(provider) -&gt; bool:
    &#34;&#34;&#34;Check connected provider

    Args:
        provider(HttpProvider): Provider
    &#34;&#34;&#34;
    return isinstance(provider, HttpProvider)


class HttpProvider(BaseProvider):
    &#34;&#34;&#34;A Connection object to make HTTP requests to a particular node.&#34;&#34;&#34;

    def __init__(self, node_url, request_kwargs=None):
        &#34;&#34;&#34;Initializes a :class:`~tronpytool.providers.http.HttpProvider`
        instance.

         Args:
            node_url (str):  Url of the node to connect to.
            request_kwargs (dict): Optional params to send with each request.

        &#34;&#34;&#34;

        self.node_url = node_url.rstrip(&#39;/&#39;)
        uri = urlparse(node_url)
        # This condition checks the node that will connect
        # to work with methods.
        if uri.scheme not in HTTP_SCHEMES:
            raise NotImplementedError(
                &#39;TronAPI does not know how to connect to scheme %r in %r&#39; % (
                    uri.scheme,
                    self.node_url,
                )
            )

        self._request_kwargs = request_kwargs or {}
        self.session = Session()

    @to_dict
    def get_request_kwargs(self):
        &#34;&#34;&#34;Header settings&#34;&#34;&#34;
        if &#39;headers&#39; not in self._request_kwargs:
            yield &#39;headers&#39;, self._http_default_headers()
        for key, value in self._request_kwargs.items():
            yield key, value

    def request(self, path, json=None, params=None, method=None):
        &#34;&#34;&#34;Performs an HTTP request with the given parameters.

           Args:
               path (str): API endpoint path (e.g.: ``&#39;/transactions&#39;``).
               json (dict): JSON data to send along with the request.
               params (dict): Dictionary of URL (query) parameters.
               method (str): HTTP method (e.g.: ``&#39;GET&#39;``).

        &#34;&#34;&#34;
        try:
            response = self._request(
                method=method,
                url=self.node_url + path if path else self.node_url,
                json=json,
                params=params,
                **self.get_request_kwargs(),
            )
        except TrxConnectionError as err:
            raise err

        return response.data

    def is_connected(self) -&gt; bool:
        &#34;&#34;&#34;Connection check

        This method sends a test request to the connected node
        to determine its health.

        Returns:
            bool: True if successful,
            False otherwise.
        &#34;&#34;&#34;
        response = self.request(path=self.status_page, method=&#39;get&#39;)
        if &#39;blockID&#39; in response or response == &#39;OK&#39;:
            return True

        return False

    def _request(self, **kwargs):

        kwargs.setdefault(&#39;timeout&#39;, 60)

        response = self.session.request(**kwargs)
        text = response.text

        try:
            json = response.json()
        except ValueError:
            json = None

        if not (200 &lt;= response.status_code &lt; 300):
            exc_cls = HTTP_EXCEPTIONS.get(response.status_code, TransportError)
            raise exc_cls(response.status_code, text, json, kwargs.get(&#39;url&#39;))

        data = json if json is not None else text
        log.debug(data)

        # Additional error interceptor that will occur in case of failed requests
        if &#39;Error&#39; in data:
            raise ValueError(data[&#39;Error&#39;])

        self.__error_manager(data)

        return HttpResponse(response.status_code, response.headers, data)

    @staticmethod
    def __error_manager(data):
        &#34;&#34;&#34;Manager error

        Args:
            data (any): response data

        &#34;&#34;&#34;
        # Additional error interceptor that will occur in case of failed requests
        if &#39;Error&#39; in data:
            raise ValueError(data[&#39;Error&#39;])

        # Convert hash errors
        if &#39;code&#39; in data and &#39;message&#39; in data:
            data[&#39;message&#39;] = to_text(hexstr=data[&#39;message&#39;])</code></pre>
</details>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="tronpytool.providers.http.is_valid_provider"><code class="name flex">
<span>def <span class="ident">is_valid_provider</span></span>(<span>provider) ‑> bool</span>
</code></dt>
<dd>
<div class="desc"><p>Check connected provider</p>
<h2 id="args">Args</h2>
<p>provider(HttpProvider): Provider</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def is_valid_provider(provider) -&gt; bool:
    &#34;&#34;&#34;Check connected provider

    Args:
        provider(HttpProvider): Provider
    &#34;&#34;&#34;
    return isinstance(provider, HttpProvider)</code></pre>
</details>
</dd>
</dl>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="tronpytool.providers.http.HttpProvider"><code class="flex name class">
<span>class <span class="ident">HttpProvider</span></span>
<span>(</span><span>node_url, request_kwargs=None)</span>
</code></dt>
<dd>
<div class="desc"><p>A Connection object to make HTTP requests to a particular node.</p>
<p>Initializes a :class:<code>~tronpytool.providers.http.HttpProvider</code>
instance.</p>
<p>Args:
node_url (str):
Url of the node to connect to.
request_kwargs (dict): Optional params to send with each request.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class HttpProvider(BaseProvider):
    &#34;&#34;&#34;A Connection object to make HTTP requests to a particular node.&#34;&#34;&#34;

    def __init__(self, node_url, request_kwargs=None):
        &#34;&#34;&#34;Initializes a :class:`~tronpytool.providers.http.HttpProvider`
        instance.

         Args:
            node_url (str):  Url of the node to connect to.
            request_kwargs (dict): Optional params to send with each request.

        &#34;&#34;&#34;

        self.node_url = node_url.rstrip(&#39;/&#39;)
        uri = urlparse(node_url)
        # This condition checks the node that will connect
        # to work with methods.
        if uri.scheme not in HTTP_SCHEMES:
            raise NotImplementedError(
                &#39;TronAPI does not know how to connect to scheme %r in %r&#39; % (
                    uri.scheme,
                    self.node_url,
                )
            )

        self._request_kwargs = request_kwargs or {}
        self.session = Session()

    @to_dict
    def get_request_kwargs(self):
        &#34;&#34;&#34;Header settings&#34;&#34;&#34;
        if &#39;headers&#39; not in self._request_kwargs:
            yield &#39;headers&#39;, self._http_default_headers()
        for key, value in self._request_kwargs.items():
            yield key, value

    def request(self, path, json=None, params=None, method=None):
        &#34;&#34;&#34;Performs an HTTP request with the given parameters.

           Args:
               path (str): API endpoint path (e.g.: ``&#39;/transactions&#39;``).
               json (dict): JSON data to send along with the request.
               params (dict): Dictionary of URL (query) parameters.
               method (str): HTTP method (e.g.: ``&#39;GET&#39;``).

        &#34;&#34;&#34;
        try:
            response = self._request(
                method=method,
                url=self.node_url + path if path else self.node_url,
                json=json,
                params=params,
                **self.get_request_kwargs(),
            )
        except TrxConnectionError as err:
            raise err

        return response.data

    def is_connected(self) -&gt; bool:
        &#34;&#34;&#34;Connection check

        This method sends a test request to the connected node
        to determine its health.

        Returns:
            bool: True if successful,
            False otherwise.
        &#34;&#34;&#34;
        response = self.request(path=self.status_page, method=&#39;get&#39;)
        if &#39;blockID&#39; in response or response == &#39;OK&#39;:
            return True

        return False

    def _request(self, **kwargs):

        kwargs.setdefault(&#39;timeout&#39;, 60)

        response = self.session.request(**kwargs)
        text = response.text

        try:
            json = response.json()
        except ValueError:
            json = None

        if not (200 &lt;= response.status_code &lt; 300):
            exc_cls = HTTP_EXCEPTIONS.get(response.status_code, TransportError)
            raise exc_cls(response.status_code, text, json, kwargs.get(&#39;url&#39;))

        data = json if json is not None else text
        log.debug(data)

        # Additional error interceptor that will occur in case of failed requests
        if &#39;Error&#39; in data:
            raise ValueError(data[&#39;Error&#39;])

        self.__error_manager(data)

        return HttpResponse(response.status_code, response.headers, data)

    @staticmethod
    def __error_manager(data):
        &#34;&#34;&#34;Manager error

        Args:
            data (any): response data

        &#34;&#34;&#34;
        # Additional error interceptor that will occur in case of failed requests
        if &#39;Error&#39; in data:
            raise ValueError(data[&#39;Error&#39;])

        # Convert hash errors
        if &#39;code&#39; in data and &#39;message&#39; in data:
            data[&#39;message&#39;] = to_text(hexstr=data[&#39;message&#39;])</code></pre>
</details>
<h3>Ancestors</h3>
<ul class="hlist">
<li><a title="tronpytool.providers.base.BaseProvider" href="base.html#tronpytool.providers.base.BaseProvider">BaseProvider</a></li>
</ul>
<h3>Methods</h3>
<dl>
<dt id="tronpytool.providers.http.HttpProvider.get_request_kwargs"><code class="name flex">
<span>def <span class="ident">get_request_kwargs</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Header settings</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@to_dict
def get_request_kwargs(self):
    &#34;&#34;&#34;Header settings&#34;&#34;&#34;
    if &#39;headers&#39; not in self._request_kwargs:
        yield &#39;headers&#39;, self._http_default_headers()
    for key, value in self._request_kwargs.items():
        yield key, value</code></pre>
</details>
</dd>
<dt id="tronpytool.providers.http.HttpProvider.is_connected"><code class="name flex">
<span>def <span class="ident">is_connected</span></span>(<span>self) ‑> bool</span>
</code></dt>
<dd>
<div class="desc"><p>Connection check</p>
<p>This method sends a test request to the connected node
to determine its health.</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>bool</code></dt>
<dd>True if successful,</dd>
</dl>
<p>False otherwise.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def is_connected(self) -&gt; bool:
    &#34;&#34;&#34;Connection check

    This method sends a test request to the connected node
    to determine its health.

    Returns:
        bool: True if successful,
        False otherwise.
    &#34;&#34;&#34;
    response = self.request(path=self.status_page, method=&#39;get&#39;)
    if &#39;blockID&#39; in response or response == &#39;OK&#39;:
        return True

    return False</code></pre>
</details>
</dd>
<dt id="tronpytool.providers.http.HttpProvider.request"><code class="name flex">
<span>def <span class="ident">request</span></span>(<span>self, path, json=None, params=None, method=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Performs an HTTP request with the given parameters.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>path</code></strong> :&ensp;<code>str</code></dt>
<dd>API endpoint path (e.g.: <code>'/transactions'</code>).</dd>
<dt><strong><code>json</code></strong> :&ensp;<code>dict</code></dt>
<dd>JSON data to send along with the request.</dd>
<dt><strong><code>params</code></strong> :&ensp;<code>dict</code></dt>
<dd>Dictionary of URL (query) parameters.</dd>
<dt><strong><code>method</code></strong> :&ensp;<code>str</code></dt>
<dd>HTTP method (e.g.: <code>'GET'</code>).</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def request(self, path, json=None, params=None, method=None):
    &#34;&#34;&#34;Performs an HTTP request with the given parameters.

       Args:
           path (str): API endpoint path (e.g.: ``&#39;/transactions&#39;``).
           json (dict): JSON data to send along with the request.
           params (dict): Dictionary of URL (query) parameters.
           method (str): HTTP method (e.g.: ``&#39;GET&#39;``).

    &#34;&#34;&#34;
    try:
        response = self._request(
            method=method,
            url=self.node_url + path if path else self.node_url,
            json=json,
            params=params,
            **self.get_request_kwargs(),
        )
    except TrxConnectionError as err:
        raise err

    return response.data</code></pre>
</details>
</dd>
</dl>
<h3>Inherited members</h3>
<ul class="hlist">
<li><code><b><a title="tronpytool.providers.base.BaseProvider" href="base.html#tronpytool.providers.base.BaseProvider">BaseProvider</a></b></code>:
<ul class="hlist">
<li><code><a title="tronpytool.providers.base.BaseProvider.format_user_agent" href="base.html#tronpytool.providers.base.BaseProvider.format_user_agent">format_user_agent</a></code></li>
<li><code><a title="tronpytool.providers.base.BaseProvider.status_page" href="base.html#tronpytool.providers.base.BaseProvider.status_page">status_page</a></code></li>
</ul>
</li>
</ul>
</dd>
<dt id="tronpytool.providers.http.HttpResponse"><code class="flex name class">
<span>class <span class="ident">HttpResponse</span></span>
<span>(</span><span>status_code, headers, data)</span>
</code></dt>
<dd>
<div class="desc"><p>HttpResponse(status_code, headers, data)</p></div>
<h3>Ancestors</h3>
<ul class="hlist">
<li>builtins.tuple</li>
</ul>
<h3>Instance variables</h3>
<dl>
<dt id="tronpytool.providers.http.HttpResponse.data"><code class="name">var <span class="ident">data</span></code></dt>
<dd>
<div class="desc"><p>Alias for field number 2</p></div>
</dd>
<dt id="tronpytool.providers.http.HttpResponse.headers"><code class="name">var <span class="ident">headers</span></code></dt>
<dd>
<div class="desc"><p>Alias for field number 1</p></div>
</dd>
<dt id="tronpytool.providers.http.HttpResponse.status_code"><code class="name">var <span class="ident">status_code</span></code></dt>
<dd>
<div class="desc"><p>Alias for field number 0</p></div>
</dd>
</dl>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<h1>Index</h1>
<div class="toc">
<ul>
<li><a href="#tronpytoolprovidershttp">tronpytool.providers.http</a></li>
</ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="tronpytool.providers" href="index.html">tronpytool.providers</a></code></li>
</ul>
</li>
<li><h3><a href="#header-functions">Functions</a></h3>
<ul class="">
<li><code><a title="tronpytool.providers.http.is_valid_provider" href="#tronpytool.providers.http.is_valid_provider">is_valid_provider</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="tronpytool.providers.http.HttpProvider" href="#tronpytool.providers.http.HttpProvider">HttpProvider</a></code></h4>
<ul class="">
<li><code><a title="tronpytool.providers.http.HttpProvider.get_request_kwargs" href="#tronpytool.providers.http.HttpProvider.get_request_kwargs">get_request_kwargs</a></code></li>
<li><code><a title="tronpytool.providers.http.HttpProvider.is_connected" href="#tronpytool.providers.http.HttpProvider.is_connected">is_connected</a></code></li>
<li><code><a title="tronpytool.providers.http.HttpProvider.request" href="#tronpytool.providers.http.HttpProvider.request">request</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="tronpytool.providers.http.HttpResponse" href="#tronpytool.providers.http.HttpResponse">HttpResponse</a></code></h4>
<ul class="">
<li><code><a title="tronpytool.providers.http.HttpResponse.data" href="#tronpytool.providers.http.HttpResponse.data">data</a></code></li>
<li><code><a title="tronpytool.providers.http.HttpResponse.headers" href="#tronpytool.providers.http.HttpResponse.headers">headers</a></code></li>
<li><code><a title="tronpytool.providers.http.HttpResponse.status_code" href="#tronpytool.providers.http.HttpResponse.status_code">status_code</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc"><cite>pdoc</cite> 0.9.1</a>.</p>
</footer>
</body>
</html>